import {listBanner, listProjects, addBanner, updateBanner, removeBanner} from '_api/home/banner'
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    bannerList: [],
    projectsList: []
  },
  mutations: {
    setBannerList(state, bannerList) {
      state.bannerList = bannerList
    },
    setProjectsList(state, projectsList) {
      state.projectsList = projectsList
    },
    addBanner(state, banner) {
      state.bannerList.unshift(banner);
    },
    updateBanner(state, banner) {
      for (let i = 0; i < state.bannerList.length; i++) {
        let existsBanner = state.bannerList[i];
        if (existsBanner.id === banner.id) {
          let keys = Object.keys(existsBanner);
          keys.forEach(key => {
            Vue.set(state.bannerList[i], key, banner[key])
          })
          break
        }
      }
    },
    removeBanner(state, banner) {
      state.bannerList = state.bannerList.filter(existsBanner => {
        if (existsBanner.id !== banner.id) {
          return existsBanner;
        }
      })
    }
  },
  actions: {
    // 获取所有新闻
    listBanner({state, commit}) {
      return _Promise(listBanner(), res => {
        commit('setBannerList', res.data)
      })
    },

    // 获取所有项目类型
    listProjects({state, commit}) {
      return _Promise(listProjects(), res => {
        commit('setProjectsList', res.data)
      })
    },

    // 添加新闻
    addBanner({state, commit}, banner) {
      return _Promise(addBanner(banner), res => {
        commit('addBanner', res.data)
      })
    },

    // 更新新闻
    updateBanner({state, commit}, banner) {
      return _Promise(updateBanner(banner), res => {
        commit('updateBanner', res.data)
      })
    },

    // 删除新闻
    removeBanner({state, commit}, banner) {
      return _Promise(removeBanner(banner.id), res => {
        commit('removeBanner', banner)
      })
    }
  }
}
